//
//  ZFBHomeQRCodeViewController.m
//  01-ZFB
//
//  Created by My Mac on 2017/6/6.
//  Copyright © 2017年 MyMac. All rights reserved.
//

#import "ZFBHomeQRCodeViewController.h"
#import "ZFBQRCodeDrawView.h"
#import <AVFoundation/AVFoundation.h>

@interface ZFBHomeQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property(nonatomic,strong) AVCaptureSession *session;

@property(nonatomic,assign) BOOL isOpenFlash;

@property(nonatomic,strong) UIBarButtonItem *rightBtn;

@end

@implementation ZFBHomeQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
}

-(void) setUpUI
{
    _rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"相册选取" style:UIBarButtonItemStyleDone target:self action:@selector(openPhotoAlbum)];
    self.navigationItem.rightBarButtonItem = _rightBtn;
    
    
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    [self session];
    
}

-(void) openPhotoAlbum
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *photoLibrary = [[UIImagePickerController alloc]init];
        photoLibrary.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        photoLibrary.delegate = self;
        [self presentViewController:photoLibrary animated:YES completion:nil];
    } else {
        [self showAlertWithTitle:@"温馨提示" message:@"该设备不支持访问相册" preferredStyle:UIAlertControllerStyleAlert actionTitle:@"返回" titleStyle:UIAlertActionStyleCancel handler:nil];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        self.tabBarController.tabBar.hidden = YES;
        [self findQRCodeFromImage:image];
    }];
}

-(void) findQRCodeFromImage:(UIImage *)image
{
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    if (features.count >= 1) {
        CIQRCodeFeature *QRCodeFeature = [features firstObject];
        [self showAlertWithTitle:@"扫描结果" message:QRCodeFeature.messageString preferredStyle:UIAlertControllerStyleAlert actionTitle:@"取消" titleStyle:UIAlertActionStyleCancel handler:nil];
    } else {
        [self showAlertWithTitle:@"扫描结果" message:@"图片中没有二维码" preferredStyle:UIAlertControllerStyleAlert actionTitle:@"取消" titleStyle:UIAlertActionStyleCancel handler:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_session startRunning];
    ZFBQRCodeDrawView *scanDrawView = [[ZFBQRCodeDrawView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64)];
    scanDrawView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:scanDrawView];
    //self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_session stopRunning];
}


//_session getter 方法  懒加载
-(AVCaptureSession *)session
{
    if (!_session) {
        _session = ({
            //获取摄像设备
            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
            //创建输入流
            AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
            if (!deviceInput) {
                return nil;
            }
            //创建输出流
            AVCaptureMetadataOutput *metadataOutput = [AVCaptureMetadataOutput new];
            //设置代理 在主线程里刷新
            [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            //设置扫描区域的比例
            CGFloat scanWidth = 300 / CGRectGetHeight(self.view.frame);
            CGFloat scanHeight = 300 / CGRectGetWidth(self.view.frame);
            metadataOutput.rectOfInterest = CGRectMake((1 - scanWidth)/2, (1 - scanHeight)/2, scanWidth, scanHeight);
            
            AVCaptureSession *tempSession = [AVCaptureSession new];
            //高质量采集率
            [tempSession setSessionPreset:AVCaptureSessionPresetHigh];
            [tempSession addInput:deviceInput];
            [tempSession addOutput:metadataOutput];
            //设置扫码支持的编码格式(这里设置条形码和二维码兼容)
            metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
            tempSession;
        });
    }
    return _session;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects firstObject];
        [self showAlertWithTitle:@"扫描结果" message:metadataObject.stringValue preferredStyle:UIAlertControllerStyleAlert actionTitle:@"返回" titleStyle:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [_session startRunning];
        }];
    }
}

@end
